package org.ns.framework.datasource.config;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.beans.BeansException;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;

/**
 * Mybatis配置管理
 * 
 * @author zhangxingyu
 *
 */
public class MybatisConfigurationManage implements ApplicationContextAware, InitializingBean {

	private ApplicationContext applicationContext;
	private Map<String, List<MybatisConfiguration>> mybatisConfigs = new HashMap<>();
	private List<MybatisConfiguration> globalConfigs = new ArrayList<>();

	@Override
	public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
		this.applicationContext = applicationContext;
	}

	public List<MybatisConfiguration> getMybatisConfigurations(String dataSourceName) {
		List<MybatisConfiguration> list = mybatisConfigs.get(dataSourceName);
		List<MybatisConfiguration> result = new ArrayList<>();
		if (globalConfigs.size() > 0) {
			result.addAll(globalConfigs);
		}
		if (list != null && list.size() > 0) {
			result.addAll(list);
		}
		return result;
	}

	@Override
	public void afterPropertiesSet() throws Exception {
		Map<String, MybatisConfiguration> configs = applicationContext.getBeansOfType(MybatisConfiguration.class);
		Map<String, List<MybatisConfiguration>> mybatisConfigs = new HashMap<>();
		List<MybatisConfiguration> globalConfigs = new ArrayList<>();
		for (MybatisConfiguration mybatisConfiguration : configs.values()) {
			String dataSourceNames[] = mybatisConfiguration.getDataSourceName();
			for (String dataSourceName : dataSourceNames) {
				if (dataSourceName.equals("*")) {
					globalConfigs.add(mybatisConfiguration);
					continue;
				}
			}
			for (String dataSourceName : dataSourceNames) {
				List<MybatisConfiguration> list = mybatisConfigs.get(dataSourceName);
				if (list == null) {
					list = new ArrayList<MybatisConfiguration>();
					mybatisConfigs.put(dataSourceName, list);
				}
				list.add(mybatisConfiguration);
			}
		}

		this.mybatisConfigs = mybatisConfigs;
		this.globalConfigs = globalConfigs;
	}

}
